package security.dao;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import security.model.Corporation;
import security.model.Organization;


@Stateless
public class OrganizationDAO {
	
	@PersistenceContext(unitName = "persistence")
    private EntityManager em;
	
	public Organization getById(Integer id){	
		return em.find(Organization.class, id);
	}
	
	public Organization save(Organization organization) {
    	em.persist(organization);
    	return organization;
    }
    
    public Organization update(Organization organization) {
    	return em.merge(organization);   
    }
    
    public void delete(Integer id) {
    	em.remove(em.find(Organization.class, id));
    }
   
	@SuppressWarnings("unchecked")
    public List<Organization> list(int first, int max) {    	
    	Query query = em.createQuery("SELECT e FROM Organization e ORDER BY e.name ASC");
    	if (max > 0) {
            query.setMaxResults(max);
        }
        if (first > 0) {
            query.setFirstResult(first);
        }
        return query.getResultList();   
    }
     
    //-------------------------------------------------------------------
    public Organization getByCode(Long code) {
        Organization result = null;
        Query query = em.createQuery("SELECT e FROM Organization e WHERE e.code=:code");
        query.setParameter("code", code);
        try {
            result = (Organization) query.getSingleResult();
        } catch (NoResultException e) {
            //e.printStackTrace();
        }
        return result;
    }

    public Long getTotal() {
        Query query = em.createQuery("SELECT COUNT(e) FROM Organization e");
        return (Long) query.getSingleResult();
    }

    
//******************************************************************************
    //NUEVO
    @SuppressWarnings("unchecked")
    public List<Organization> listByCorporation(Corporation corporation) {
        Query query = em.createQuery("SELECT e FROM Organization e WHERE e.corporation = :corporation ORDER BY e.name ASC");
        query.setParameter("corporation", corporation);
        return query.getResultList();
    }
    

    //******************************************************************************
    //NUEVO
    public Organization getByAlias(String alias) {
        Organization result = null;
        Query query = em.createQuery("SELECT e FROM Organization e WHERE e.alias=:alias");
        query.setParameter("alias",alias);
        try {
            result = (Organization) query.getSingleResult();
        } catch (NoResultException e) {
            //e.printStackTrace();
        }
        return result;
    }

}
